package com.liu.demo1.testDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liusiyu
 * @ClassName LockTest
 * @date 2022年01月14日 10:00
 */
public class LockTest {

    private Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        LockTest lockTest = new LockTest();
        Thread t1 = new Thread(() -> lockTest.method(Thread.currentThread()),"t1");
        Thread t2 = new Thread(() -> lockTest.method(Thread.currentThread()),"t2");
        t1.start();
        t2.start();
    }

    public void method(Thread thread){
        /*lock.lock();
        try {
            System.out.println("线程名"+thread.getName()+"获得了锁");
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            System.out.println("线程名"+thread.getName()+"释放了锁");
            lock.unlock();
        }*/
        if (lock.tryLock()){
            try {
                System.out.println("线程名"+thread.getName()+"获得了锁");
            }catch (Exception e ){
                e.printStackTrace();
            }finally {
                System.out.println("线程名"+thread.getName()+"释放了锁");
                lock.unlock();
            }
        }else {
            System.out.println("我是"+Thread.currentThread().getName()+"有人占着锁，我进不去");
        }
    }
}
